var express = require('express');
var router = express.Router();

/* 查询图书类别信息 */
router.get('/getClassifyInfo', function (req, res, next) {
    var search = req.body
    MongoClient.connect(config.url, function (err, client) {
        if (err) {
            console.log('数据库连接失败！', err)
            res.json({ code: 200, message: 'error', data: err })
        } else {
            var db = client.db()
            db.collection('classify').aggregate([
                { $match: { classify_id: `/^${search}/gi ` } } //查询的筛选条件
            ])
                .toArray(function (err, result) {
                    if (err) {
                        console.log('查询数据失败！', err)
                    } else {
                        res.json({ code: 200, message: 'ok', data: result })
                        client.close()
                    }
                })
        }
    })
});

/* 添加图书类别 */
router.get('/addClassify', function (req, res, next) {
    var insertClassify = req.body
    MongoClient.connect(config.url, function (err, client) {
        if (err) {
            console.log('数据库连接失败！', err)
            res.json({ code: 200, message: 'error', data: err })
        } else {
            var db = client.db()
            var addClassify = {
                classify_id: '',
                books_classify: insertClassify.books_classify,
                classify_parent: insertClassify.classify_parent,
                classify_grandpar: insertClassify.classify_grandpar,
            }
            db.collection('classify').insertOne(addClassify, function (err, result) {
                if (err) {
                    console.log('添加数据失败！', err)
                } else {
                    res.json({ code: 200, message: 'ok', data: result })
                    client.close()
                }
            })
        }
    })
});

/* 删除图书类别 */
router.get('/delClassify', function (req, res, next) {
    var deleteClassify = req.body
    MongoClient.connect(config.url, function (err, client) {
        if (err) {
            console.log('数据库连接失败！', err)
            res.json({ code: 200, message: 'error', data: err })
        } else {
            var db = client.db()
            db.collection('classify').deleteOne({ books_classify: deleteClassify.books_classify }, function (err, result) {
                if (err) {
                    console.log('删除数据失败！', err)
                } else {
                    //4.返回结果{code:0;message:'ok',data:{}}
                    res.json({ code: 200, message: 'ok', data: result })
                    client.close()
                }
            })
        }
    })
});

/* 修改图书类别 */
router.get('/updClassify', function (req, res, next) {
    res.send('respond with a resource');
});
module.exports = router;